package org.ucas.faker.web.service.similar;

import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ucas.faker.web.fetcher.FetchExecutor;
import org.ucas.faker.web.fetcher.FetchReqBuilder;
import org.ucas.faker.web.fetcher.FetchResult;
import org.ucas.faker.web.service.PatentService;
import org.ucas.faker.web.utils.model.RawPatent;
import org.ucas.faker.web.utils.mql.ranker.MqlBatchRanker;
import org.ucas.faker.web.utils.mql.ranker.MqlBatchRanker.BatchResult;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service
@Transactional
public class SimilarService {
    @Autowired private FetchExecutor fetcher;
    @Autowired private PatentService patentService;

    public List<Pair<RawPatent, Float>>  getSimilarPatent(String mql, long depotId) throws InterruptedException {
        FetchReqBuilder requestBuilder = FetchReqBuilder.instance().select("id").depot(depotId);
        FetchResult fetchResult = fetcher.fetch(requestBuilder.build());
        List<Long> idList = fetchResult.<Long>column("id");
        List<RawPatent> patentList = patentService.loadBatch(idList);

        MqlBatchRanker ranker = new MqlBatchRanker(mql, patentList);
        ranker.rank();
        while (!ranker.done()){
            Thread.sleep(300);
        }
        ranker.accept();
        List<Pair<RawPatent, Float>> batchResultList = ranker.batch();
        return batchResultList;
    }
    public List<RawPatent>  getSimilarPatentList(String mql, long depotId) throws InterruptedException {
        FetchReqBuilder requestBuilder = FetchReqBuilder.instance().select("id").depot(depotId);
        FetchResult fetchResult = fetcher.fetch(requestBuilder.build());
        List<Long> idList = fetchResult.<Long>column("id");
        System.out.println("idList="+idList.size());
        List<RawPatent> patentList = patentService.loadBatch(idList);
        System.out.println("patentList="+patentList.size());

        MqlBatchRanker ranker = new MqlBatchRanker(mql, patentList);
        ranker.rank();
        while (!ranker.done()){
            System.out.println("rank");
            Thread.sleep(300);
        }
        ranker.accept();
        System.out.println("ranker");
        List<Pair<RawPatent, Float>> batchResultList = ranker.batch();
        List<RawPatent> res = new ArrayList<>();
        for(Pair<RawPatent, Float> pair : batchResultList) {
        	res.add(pair.getLeft());
        }
        return res;
    }
    
    
}
